package com.keepers.repair.service;

import android.annotation.TargetApi;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.blankj.utilcode.util.ServiceUtils;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.utils.AlertToast;


/**
 * JobService，支持5.0以上forcestop依然有效
 */
@TargetApi(21)
public class AliveJobService extends JobService {
    // 告知编译器，这个变量不能被优化

    private static final int MESSAGE_ID_TASK = 0x01;

    private Handler mHandler = new Handler(msg -> {
        if (ServiceUtils.isServiceRunning(SocketService.class)) {
            LogUtil.e("服务活着...");
            AlertToast.show("服务活着...");
        } else {
            Intent intent = new Intent(getApplicationContext(), SocketService.class);
            startService(intent);
            LogUtil.e("重启服务...");
            AlertToast.show("重启服务...");
        }
        // 通知系统任务执行结束
        jobFinished((JobParameters) msg.obj, false);
        return true;
    });

    @Override
    public boolean onStartJob(JobParameters params) {
        LogUtil.e("KeepAliveService----->JobService服务被启动...");
        // 返回false，系统假设这个方法返回时任务已经执行完毕；
        // 返回true，系统假定这个任务正要被执行
        Message msg = Message.obtain(mHandler, MESSAGE_ID_TASK, params);
        mHandler.sendMessage(msg);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        mHandler.removeMessages(MESSAGE_ID_TASK);
        LogUtil.e("KeepAliveService----->JobService服务被关闭");
        return false;
    }
}
